#include "udp_server.hpp"
#include <memory>
#include <string>

using namespace udp_server;

// 使用手册
static void usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " serverip serverport\n"
              << std::endl;
}

// 业务处理环节：
std::string transactionString(std::string resquest) // 大小写转换
{
    std::string result;
    char c;
    for (auto &r : resquest)
    {
        if (islower(r)) c = toupper(r);// 小写字母转大写
        result += c;
    }
    return result;
}

bool isPass(std::string command)
{
    bool pass = true;
    size_t re = command.find("rm");
    if(re != string::npos) pass = false;
    re = command.find("mv");
    if(re != string::npos) pass = false;
    re = command.find("while");
    if(re != string::npos) pass = false;

    return pass;
}

std::string excuteCommand(std::string command) // 通过客户端发送的命令，在服务端上进行执行
{   
    //安全检查
    if(!isPass(command)) return "you are bad man!";

    //创建管道、创建子进程，执行command命令结果返回到fp文件中
    FILE* fp = popen(command.c_str(), "r"); //命令是只读的
    if(fp == nullptr)
    {
        return "创建子进程/管道失败";
    }

    char line[1024];
    std::string result;
    while(fgets(line, sizeof(line), fp) != nullptr) //从fp文件中读取内容存储到line缓冲区中(按行读取)
    {
        result += line;
    }

    //关闭管道、回收子进程
    pclose(fp);

    return result;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);

    // unique_ptr<UdpServer> userver(new UdpServer(transactionString, port));
    unique_ptr<UdpServer> userver(new UdpServer(excuteCommand, port));

    // 初始化服务器
    userver->InitServer();

    userver->Start();

    return 0;
}